import { App, epclass, navigate, storage } from '../../../library/api/index'
var helper = require('../../../library/helper.js')

Page({
  data: {
    navIndex: 'on',
    playBtn: 'https://r.epclass.meadjohnson.joypaw.com/p/v2/icon_59.png',
    expert: {
      false: {
        0: 'float question_1 question_2',
        1: 'float time_1 time_2'
      },
      true: {
        0: 'float question_1',
        1: 'float time_1'
      }
    },
    class: {
      id: null
    },
    isLiveEnd: false,
    isAudio: true,
    getInteractionsInterval: null,
    showVideoArea: false,
    videoCtx: null,
    audioCurrentPercent: 0,
    audioCurrentDurationText: '0:00',
    isPlayEnd: false,
    userWord: '',
    hostWords: [],
    replays: [],
    userWords: [],
    hideClassSummary: false,
    audioCtx: null,
    socketOpen: false,
    socketMsgQueue: [],
    onlineCount: 0,
    replayScrollTop: 5,
    replayScrollHeight: 100,
    textScrollTop: 5,
    textScrollHeight: 100,
    interactionScrollTop: 5,
    interactionScrollHeight: 60,
    lastQuestionId: '',
    tip: 'blank',
    tipData: {},
    liveStatus: null
  },
  onLoad: function(e) {
    this.setData({
      class: {
        id: e.cid
      }
    })
    App.jice.onLoad(e)
  },
  onReady: function() {
    epclass.getClass({cid: this.data.class.id}, r => {
      if(r.code == 200) {
        if(r.data.status == 10) {
          if(r.data.live_type == 2) {
            this.data.isAudio = false
          }
          if(r.data.duration_time < r.data.process) {
            this.data.isLiveEnd = true
          }
          this.setData({
            class: r.data,
            isLiveEnd: this.data.isLiveEnd,
            isAudio: this.data.isAudio
          })
        } else if(r.data.status == 9) {
          this.showGoIndexTip('课堂还未开始，请耐心等待')
        } else if(r.data.status == 8) {
          this.showWaitReviewTip()
        } else if(r.data.status == 7) {
          this.goReview()
        }
        !r.data.is_apply ? this.autoApplyClass() : null;
        if(this.data.isAudio && !this.data.isLiveEnd) {
          this.startAudioLiving()
        } else if(this.data.isAudio && this.data.isLiveEnd) {
          this.onEndAudioLiving()
        }
        if(!this.data.isAudio && this.data.isLiveEnd) {
          this.endVideoLiving()
        }
      }
    })
    this.host()
    this.getInteractions()
    this.initSocketServer()
    //this.data.getInteractionsInterval = setInterval(() => {
    //this.getInteractions()
    //}, 5000)
    //this.setData({
    //  getInteractionsInterval: this.data.getInteractionsInterval
    //})
    this.setUserHistoryWords()
    App.jice.track('page', {
      pagepath: '/pages/epclass/live/index',
      pageTitle: '直播',
      pageType: 'view'
    })
    App.logger({
      type: App.G.view,
      channel: App.G.channel,
      target: '直播页面',
      class_id: this.data.class.id
    })
  },
  onShow: function() {
    if(this.audioCtx !== undefined && this.audioCtx !== null) {
      this.send(JSON.stringify({
        act: 'online'
      }))
    }
    App.jice.track('appshow')
  },
  onHide: function() {
  },
  onUnload: function() {
    console.log('onUnload')
    if(this.data.getInteractionsInterval != null) {
      //clearInterval(this.data.getInteractionsInterval)
      this.setData({
        getInteractionsInterval: null
      })
    }
  },
  startVideoLiving: function() {
    if(this.data.isLiveEnd) {
      this.showErrorTip('视频课堂已经结束，您可以在互动专区向专家提问~')
      return
    }
    this.setData({
      showVideoArea: true
    })
    if(!this.data.videoCtx) {
      this.data.videoCtx = wx.createVideoContext('myVideo')
      this.data.videoCtx.play()
    }
  },
  showVideoArea: function() {
    if(this.data.videoCtx) {
      this.setData({
        showVideoArea: true
      })
    }
  },
  hideVideoArea: function() {
    this.setData({
      showVideoArea: false
    })
  },
  endVideoLiving: function() {
    this.endLiving()
  },
  startAudioLiving: function() {
    this.audioCtx = wx.createAudioContext('myAudio')
    setTimeout(() => {
      var start = this.data.class.now - this.data.class.start
      var audio_duration = helper.strToSecond(this.data.class.audio_duration)
      if(start >= audio_duration) {
        this.onEndAudioLiving()
      } else {
        this.audioCtx.play()
        this.audioCtx.seek(start)
      }
    }, 500)
  },
  onAudioLiving: function(e) {
    setTimeout(() => {
      this.setData({
        audioCurrentPercent: (e.detail.currentTime / e.detail.duration) * 100,
        audioCurrentDurationText: helper.secondToStr(e.detail.currentTime)
      })
    }, 1000)
  },
  onEndAudioLiving: function() {
    this.setData({
      playBtn: 'https://r.epclass.meadjohnson.joypaw.com/p/v2/icon_15.png',
      audioCurrentPercent: 100,
      audioCurrentDurationText: this.data.class.audio_duration,
      isPlayEnd: true
    })
    this.endLiving()
  },
  endLiving() {
    this.replays()
  },
  ask: function() {
    this.setData({
      tip: 'ask',
      tipData: this.data.userWord
    })
  },
  setUserHistoryWords: function() {
    storage.get('word').then(ret => {
      this.data.userWord = ret
      setTimeout(() => {
        this.setData({
          userWord: this.data.userWord
        })
      }, 500)
    })
  },
  getWords: function(e) {
    this.setData({
      userWord: e.detail.value
    })
  },
  say: function(e) {
    if(this.data.userWord == '') {
      this.showErrorTip('请输入您想说的话~')
      return
    }
    var post = {
      cid: this.data.class.id,
      word: this.data.userWord
    }
    storage.set('word', post.word)
    epclass.ask(post, r => {
      if(r.code == 201) {
        this.askRegister()
      } else if(r.code == 202) {
        this.showErrorTip('避免刷屏，请一分钟后再试~')
      } else if(r.code == 200) {
        storage.remove('word')
        this.setData({userWord: ''})
        this.closeTip()
        this.saySuccessCallback()
        this.showErrorTip(r.msg)
      } else if(r.code == 502) {
        this.showErrorTip('内容长度不能多于20个字~')
      } else {
        this.showErrorTip(r.msg)
      }
    }, r => {
      console.log(r)
      this.showErrorTip('系统错误，请稍后再试~')
    })
  },
  saySuccessCallback: function() {
    this.send(JSON.stringify({
      act: 'syncInteractions',
      cid: this.data.class.id,
    }))
  },
  host: function() {
    epclass.host({class_id: this.data.class.id}, r => {
      if(r.code == 200) {
        if(r.data.length > 0) {
          this.setData({
            hostWords: r.data
          })
        }
      }
    })
  },
  replays: function() {
    epclass.replay({
      cid: this.data.class.id,
      count: 0
    }, r => {
      if(r.code == 200) {
        if(r.data.length > 0) {
          for(var i = 0; i < r.data.length; i++) {
            r.data[i]['v_c'] = 'audio_img'
            this.data.replays.push(r.data[i]);
          }
          this.setData({
            hideClassSummary: true,
            replays: this.data.replays
          })
          setTimeout(() => {
            this.setData({
              lastQuestionId: this.data.replays[this.data.replays.length - 1].id
            }, 500)
          })
        }
      }
    })
  },
  getCurrentStatus: function() {
    epclass.getClassStatus({class_id: this.data.class.id}, r => {
      if(r.code == 200) {
        if(r.data !== 10) {
          clearInterval(this.data.liveStatus);
          this.showGoIndexTip('课程已经结束，敬请期待下次开课~')
        }
      }
    })
  },
  getInteractions: function() {
    var lastId = this.data.userWords.length > 0 ? this.data.userWords[0]['id'] : 0;
    epclass.interactions({
      cid: this.data.class.id,
      last_id: lastId
    }, r => {
      if(r.code == 200) {
        if(r.data.length > 0) {
          for(var i = 0; i < r.data.length; i++) {
            this.data.userWords.unshift(r.data[i]);
          }
          this.setData({
            userWords: this.data.userWords
          })
        }
      } else {
        this.showErrorTip(r.data)
      }
    })
  },
  initSocketServer: function() {
    this.loadServer()
    wx.onSocketClose((res) => {
      this.setData({
        socketOpen: false
      })
    })
    wx.onSocketError((res) => {
      this.loadServer()
    })
    wx.onSocketMessage((res) => {
      var data = JSON.parse(res.data.trim())
      if(data.act == 'online') {
        this.setData({
          onlineCount: data.data
        })
      }
      if(data.act == 'syncHost') {
        this.setHostWords(data.data)
      }
      if(data.act == 'syncExpert') {
        this.setReplays(data.data)
      }
      if(data.act == 'syncInteractions') {
        this.getInteractions()
      }
      if(data.act == 'endLive') {
        wx.closeSocket()
        this.getCurrentStatus();
        if(this.data.liveStatus == null) {
          this.data.liveStatus = setInterval(() => {
            this.getCurrentStatus()
          }, 10000)
        }
      }
      if(data.act === 'endVideoLive') {
        this.showErrorTip('视频课堂已经结束，您可以在互动专区向专家提问~')
        this.setData({
          isLiveEnd: true
        })
        this.replays()
      }
    })
  },
  loadServer: function() {
    wx.closeSocket()
    wx.connectSocket({
      url: App.G.Wss
    })
    wx.onSocketOpen((res) => {
      this.setData({
        socketOpen: true
      })
    })
  },
  send: function(msg) {
    if(msg != null) {
      this.data.socketMsgQueue.push(msg)
      this.setData({
        socketMsgQueue: this.data.socketMsgQueue
      })
    }
    if(this.data.socketOpen) {
      for(var i = 0; i < this.data.socketMsgQueue.length; i++) {
        if(this.data.socketMsgQueue[i] !== null) {
          wx.sendSocketMessage({
            data: this.data.socketMsgQueue[i],
            success: function() {
              console.log('send')
            }
          })
        }
      }
      this.setData({
        socketMsgQueue: []
      })
    } else {
      console.log('socket close')
      this.loadServer()
    }
  },
  getUserWords: function() {
    this.send(JSON.stringify({
      act: 'getUserWords',
      cid: this.data.class.id,
      count: this.data.userWords.length
    }))
  },
  setHostWords: function(data) {
    this.setData({
      hostWords: data
    })
  },
  setReplays: function(data) {
    if(data.length > 0) {
      for(var i = 0; i < data.length; i++) {
        var isLoaded = false
        for(var j = 0; j < this.data.replays.length; j++) {
          if(data[i]['id'] == this.data.replays[j]['id']) {
            isLoaded = true
          }
        }
        if(!isLoaded) {
          data[i]['v_c'] = 'audio_img'
          this.data.replays.push(data[i])
        }
      }
      this.setData({
        hideClassSummary: true,
        replays: this.data.replays
      })
      setTimeout(() => {
        this.setData({
          lastQuestionId: this.data.replays[this.data.replays.length - 1].id
        }, 500)
      })
    } else {
      this.setData({
        hideClassSummary: false
      })
    }
  },
  currentReplayAudioCtx: null,
  currentReplayAudioCtxPlaying: null,
  currentReplayAudioCtxId: null,
  playReplay: function(event) {
    var clickId = event.target.dataset.id
    var clickAudioId = 'v-' + clickId
    if(this.currentReplayAudioCtx != null) {
      if(clickId == this.currentReplayAudioCtxId) {
        if(this.currentReplayAudioCtxPlaying) {
          this.currentReplayAudioCtx.pause()
          this.currentReplayAudioCtxPlaying = false
          this.changeReplayBarStyleByPlayStatus(clickId, false)
        } else {
          this.currentReplayAudioCtx.play()
          this.currentReplayAudioCtxPlaying = true
          this.changeReplayBarStyleByPlayStatus(clickId, true)
        }
      } else {
        // 播放对象改变,停止去掉当前currentReplay*变量赋值
        this.currentReplayAudioCtx.pause()
        this.currentReplayAudioCtx = null
        this.changeReplayBarStyleByPlayStatus(this.currentReplayAudioCtxId, false)
        // 把当前播放对象指定到currentReplay*变量上
        this.currentReplayAudioCtx = wx.createAudioContext(clickAudioId)
        this.currentReplayAudioCtxId = clickId
        this.currentReplayAudioCtx.play()
        this.currentReplayAudioCtxPlaying = true
        this.changeReplayBarStyleByPlayStatus(clickId, true)
      }
    } else {
      this.currentReplayAudioCtx = wx.createAudioContext(clickAudioId)
      this.currentReplayAudioCtxId = clickId
      this.currentReplayAudioCtx.play()
      this.currentReplayAudioCtxPlaying = true
      this.changeReplayBarStyleByPlayStatus(clickId, true)
    }
  },
  playReplayEnd: function(e) {
    this.changeReplayBarStyleByPlayStatus(this.currentReplayAudioCtxId, false)
    this.currentReplayAudioCtx = null
    this.currentReplayAudioCtxPlaying = null
    this.currentReplayAudioCtxId = null
  },
  changeReplayBarStyleByPlayStatus: function(id, isPlay) {
    for(var i = 0; i < this.data.replays.length; i++) {
      if(this.data.replays[i]['id'] == id) {
        if(isPlay) {
          this.data.replays[i]['v_c'] = 'audio_img play'
        } else {
          this.data.replays[i]['v_c'] = 'audio_img'
        }
        break
      }
    }
    this.setData({
      replays: this.data.replays
    })
  },
  onReplayScroll: function(e) {
    this.setData({
      replayScrollTop: e.detail.scrollTop * 232 / e.detail.scrollHeight + 5,
      replayScrollHeight: 232 / e.detail.scrollHeight * 232 - 2
    })
  },
  onTextScroll: function(e) {
    this.setData({
      textScrollTop: e.detail.scrollTop * 112 / e.detail.scrollHeight + 5,
      textScrollHeight: 112 / e.detail.scrollHeight * 112 - 2
    })
  },
  onInteractionsScroll: function(e) {
    this.setData({
      interactionScrollTop: e.detail.scrollTop * 105 / e.detail.scrollHeight + 5,
      interactionScrollHeight: 105 / e.detail.scrollHeight * 105 - 2
    })
  },
  like: function() {
    epclass.like({cid: this.data.class.id}, r => {
      if(r.code == 200) {
        this.data.class.like_count = r.like_count
        this.setData({
          class: this.data.class
        })
        this.send(JSON.stringify({
          act: 'newLike',
          cid: this.data.class.id
        }))
      } else {
        this.showErrorTip(r.message)
      }
    })
  },
  autoApplyClass: function() {
    epclass.autoApply({cid: this.data.class.id}, r => {
      console.log(r)
    })
  },
  toRegister: function() {
    navigate.to('/pages/register/index?from=' + encodeURIComponent('/pages/epclass/live/index?cid=' + this.data.class.id))
  },
  showExpert: function() {
    this.setData({
      tip: 'expert',
      tipData: {
        expert: this.data.class.expert
      }
    })
    this.hideVideoArea()
  },
  closeExpertTip: function() {
    this.setData({
      tip: 'blank',
      tipData: {}
    })
    this.showVideoArea()
  },
  closeWaitTip: function() {
    this.goIndex()
  },
  askRegister: function() {
    this.setData({
      tip: 'ask_register',
      tipData: {}
    })
  },
  showErrorTip: function(msg) {
    this.setData({
      tip: 'error_tip',
      tipData: msg
    })
    this.hideVideoArea()
  },
  showWaitReviewTip: function() {
    this.setData({
      tip: 'wait_review'
    })
  },
  showGoIndexTip: function(msg) {
    this.setData({
      tip: 'go_index_tip',
      tipData: msg
    })
  },
  closeTip: function() {
    this.setData({
      tip: 'blank',
      tipData: {}
    })
    this.showVideoArea()
  },
  mall: function() {
    this.setData({
      tip: 'go_mall_tip'
    })
  },
  goMall: function() {
    navigate.to('/pages/mall/index')
  },
  goIndex() {
    navigate.redirect(`/pages/index/index`);
  },
  goReview() {
    navigate.redirect(`/pages/epclass/review/index?cid=` + this.data.class.id);
  },
  onShareAppMessage: function() {
    App.jice.track('onshare', {
      shareto: 'friend',
      title: `与专家对话，做A+妈妈！【${this.data.class.name}】正在开课`,
      path: `/pages/epclass/live/index?cid=${this.data.class.id}`
    })
    return {
      title: `与专家对话，做A+妈妈！【${this.data.class.name}】正在开课`,
      desc: `与专家对话，做A+妈妈~【${this.data.class.name}】正在播放中，再不戳进来，专家就要下班了`,
      path: `/pages/epclass/live/index?cid=${this.data.class.id}`,
      success: () => {
        epclass.shareLogger({
          class_id: this.data.class.id,
          target: '课程开课',
          action: 'appMessage'
        }, r => {
        })
      }
    }
  }
})
